package com.ferris.redbook.service.impl;

import com.ferris.redbook.dto.response.UserResponse;
import com.ferris.redbook.entity.User;
import com.ferris.redbook.mapper.UserMapper;
import com.ferris.redbook.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Value("${app.upload.access-url-base}")
    private String accessUrlBase;

    @Override
    public UserResponse getCurrentUserInfo(Long userId) {
        return Optional.ofNullable(userMapper.selectById(userId))
                .map(this::convertToResponseWithStats)
                .orElse(null);
    }

    @Override
    public UserResponse getUserById(Long userId) {
        return Optional.ofNullable(userMapper.selectById(userId))
                .map(this::convertToResponse)
                .orElse(null);
    }

    /**
     * 转换用户实体为响应对象（带统计信息）
     */
    private UserResponse convertToResponseWithStats(User user) {
        UserResponse response = convertToResponse(user);

        // 使用 Java 8 Stream 和 Optional 处理统计信息
        Long followCount = Optional.ofNullable(userMapper.countFollows(user.getId()))
                .orElse(0L);
        Long fansCount = Optional.ofNullable(userMapper.countFans(user.getId()))
                .orElse(0L);
        Long likedCount = Optional.ofNullable(userMapper.countLikedPosts(user.getId()))
                .orElse(0L);

        response.setFollowCount(followCount);
        response.setFansCount(fansCount);
        response.setLikedCount(likedCount);

        return response;
    }

    /**
     * 转换用户实体为响应对象
     */
    private UserResponse convertToResponse(User user) {
        // 在 UserServiceImpl 中
        String avatarUrl = accessUrlBase + "/" + user.getAvatar();

        return UserResponse.builder()
                .id(user.getId())
                .email(user.getEmail())
                .nickname(user.getNickname())
                .avatar(avatarUrl)
                .bio(user.getBio())
                .gender(user.getGender())
                .location(user.getLocation())
                .birthday(user.getBirthday())
                .createdAt(user.getCreatedAt())
                .build();
    }
}